from PyQt5.QtCore import Qt
from 数据库 import de_alter
from PyQt5.QtWidgets import QApplication, QDialog, QMessageBox,  QTableWidgetItem
import sys
import pymysql

class MainDialog(QDialog):
    def __init__(self, parent=None):
        super(QDialog, self).__init__(parent)
        self.ui = de_alter.Ui_Dialog()
        self.ui.setupUi(self)


    def append(self, zonta, result, column, table):
        self.result = result
        self.column = column
        self.table = table
        self.ui.tableWidget.setColumnCount(len(zonta))
        self.ui.tableWidget_2.setColumnCount(len(zonta))
        self.ui.tableWidget_2.setRowCount(1)
        self.zonta = zonta
        self.ui.tableWidget.setHorizontalHeaderLabels(zonta)
        for i in range(len(result)):
            if i == column:
                item = QTableWidgetItem(None)
                item.setFlags(Qt.ItemFlag(63))
            else:
                item = QTableWidgetItem(result[i])
                item.setTextAlignment(Qt.AlignCenter | Qt.AlignBottom)
                item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
            self.ui.tableWidget_2.setItem(0, i, item)
        self.show()

    def alter(self):
        conn = pymysql.connect(host='127.0.0.1', user='root', passwd='dqzx2020', port=3306, db='design', charset='utf8')
        num_k = self.zonta[0]
        num_v = self.result[0]
        key = self.zonta[self.column]
        if not self.ui.tableWidget_2.item(0, self.column) or not self.ui.tableWidget_2.item(0, self.column).text():
            QMessageBox.about(self, ' ', '请输入要修改后的值（空值为null）')
        else:
            cur = conn.cursor()
            value = self.ui.tableWidget_2.item(0, self.column).text()
            if self.table == '采购明细':
                sql = "update {} set {} = '{}' where {} = '{}'".format(self.table, key, value, num_k, num_v)
            else:
                sql = "update {} set {} = '{}' where {} = '{}'".format(self.table[0:-2], key, value, num_k, num_v)
            cur.execute(sql)
            conn.commit()
            QMessageBox.about(self, ' ', '修改成功,记得重新查询一次刷新页面')
            conn.close()
            self.hide()
if __name__ == '__main__':
    myapp = QApplication(sys.argv)
    myDlg = MainDialog()
    myDlg.show()
    sys.exit(myapp.exec_())